package com.equipment.system.web.api;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.equipment.system.entity.EquipmentVersion;
import com.equipment.system.service.EquipmentVersionService;
import com.equipment.system.web.annotation.ApiEncrypt;
import com.equipment.system.web.utils.Rest;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * ${DESCRIPTION}
 *
 * @author 杨凯
 * @create 2018-03-26 14:31
 **/
@RestController
@RequestMapping("/version")
public class EquipmentVersionController {
	private static final Logger LOGGER = LoggerFactory.getLogger(EquipmentVersionController.class);


	@Autowired
	private EquipmentVersionService versionService;


	private final String downloadUrl = "http://192.168.1.107:8081/version/download";


	@ApiEncrypt(encode = true)
	@PostMapping("/check")
	public Rest checkClientVersion(){
		Rest.Builder rest = Rest.newBuilder();
		EntityWrapper wrapper = new EntityWrapper<EquipmentVersion>();
		wrapper.orderBy("id",false).last("LIMIT 1");
		EquipmentVersion equipmentVersion = versionService.selectOne(wrapper);
		rest.put("version",equipmentVersion.getVersion());
		rest.put("url",downloadUrl);
		rest.status(200);
		return rest.build();
	}



	@GetMapping("/list")
	public Map<String,Object> equipmentList(@RequestParam(defaultValue = "0") int start, @RequestParam(defaultValue = "10") int length){
		Map<String,Object> map = new HashMap<>(3);
		Page page = new Page(start, length);
		Page<EquipmentVersion> paperPage = versionService.selectPage(page);
		Integer count = paperPage.getTotal();
		List<EquipmentVersion> list = paperPage.getRecords();
		map.put("data", list);
		map.put("count",count);
		return map;
	}

	@PostMapping("/add")
	public Rest addEquipment(EquipmentVersion version){
		Rest.Builder rest = Rest.newBuilder();
		version.setCreated(new Timestamp(System.currentTimeMillis()));
		versionService.insert(version);
		return rest.build();
	}



	@PostMapping("/upload")
	public Rest upload(MultipartFile file){
		Rest.Builder rest = Rest.newBuilder();
		if (Objects.isNull(file) || file.isEmpty()) {
			LOGGER.error("文件为空");
		}
		try {
			byte[] bytes = file.getBytes();
			Path path = Paths.get("c://file/" + file.getOriginalFilename());
			//如果没有files文件夹，则创建
			if (!Files.isWritable(path)) {
				Files.createDirectories(Paths.get("c://file/"));
			}
			//文件写入指定路径
			Files.write(path, bytes);
			String url = "c://file/"+file.getOriginalFilename();
			LOGGER.info("文件写入成功...");
			rest.put("url",url);
			return rest.status(2000).build();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return rest.build();
	}

	@RequestMapping("/download")
	public ResponseEntity<byte[]> download(Integer id) throws IOException {

		EntityWrapper wrapper = new EntityWrapper<EquipmentVersion>();
		if(ObjectUtils.allNotNull(id)){
			wrapper.eq("id",id);
		}
		wrapper.orderBy("id",false).last("LIMIT 1");;
		EquipmentVersion equipmentVersion = versionService.selectOne(wrapper);
		File file = new File(equipmentVersion.getUrl());
		InputStream is = new FileInputStream(file);
		byte[] body = new byte[is.available()];
		is.read(body);
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Disposition", "attachment;filename=" + file.getName());
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		HttpStatus statusCode = HttpStatus.OK;
		ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
		return entity;
	}
}
